package com.css.ids.server.util;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
public class ZipByteUtil {
	/**
	 * 压缩输入流
	 * @param src 输入流
	 * @return  
	 * @throws IOException 异常
	 */
	public static byte[] zip(InputStream src)throws IOException{
		byte[] buf = new byte[1024];
		int readBytes = 0;
		java.io.ByteArrayOutputStream bos = new java.io.ByteArrayOutputStream();
		java.util.zip.GZIPOutputStream zos = new java.util.zip.GZIPOutputStream(bos);
		while((readBytes = src.read(buf)) != -1){
			zos.write(buf, 0, readBytes);
		}
		zos.close();
		return bos.toByteArray();
	}
	
	public static byte[] unzip(byte[]  target)throws IOException{
		byte[] buf = new byte[1024];
		int readBytes = 0;
		java.io.ByteArrayOutputStream bos = new java.io.ByteArrayOutputStream();
		java.util.zip.GZIPInputStream zipIn = new java.util.zip.GZIPInputStream(new java.io.ByteArrayInputStream(target));
		while((readBytes = zipIn.read(buf)) != -1){
			bos.write(buf, 0, readBytes);
		}		
		zipIn.close();
		return bos.toByteArray();
	}
	
	public static String getString(byte[] data,String charsetName) throws UnsupportedEncodingException{
		if(data==null){return "";}
		byte[] target = new byte[]{};
		try {
			target = ZipByteUtil.unzip(data);
		} catch (IOException e) {
			e.printStackTrace();
		}
		if(target==null){return "";}
		return new String(target,charsetName);
	}
	
	public static void main(String[] args) throws Exception {
		String xml = "<root><xml>content.length</xml><xml>content.length</xml><xml>content.length</xml><xml>content.length</xml><xml>content.length</xml><xml>content.length</xml><xml>content.length</xml><xml>content.length</xml><xml>content.length</xml><xml>content.length</xml></root>";
		byte[] bytes = xml.getBytes();	
		byte[] zipBytes = zip(new java.io.ByteArrayInputStream(bytes));
		
		byte[] target =unzip(zipBytes);
		System.out.println("原长度: "+bytes.length+",目标长度: "+zipBytes.length+",解压缩后长度: "+new String(target));
		
		
	}
}